package com.ktjy.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

@Component
public class JwtTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //登录用户信息
        String str=request.getHeader("Authorization");
        if(str==null){
            filterChain.doFilter(request,response);
        }
        if (str.startsWith("Bearer "))
        {
            str = str.replace("Bearer ", "");
        }

        Claims claims = Jwts.parser()
                .setSigningKey("zjgdzjgdzjgdzjgdzjgdzjgdzjgdzjgdzjgdzjgdzjgdzjgds")
                .build()
                .parseClaimsJws(str)
                .getBody();

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(
                        claims.get("username"),
                        claims.get("password"),
                        AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}
